<template>
  <el-dialog :append-to-body="true" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'"
             width="800px">
    <question-bank ref="questionBank" @setQuestionInfo="setQuestionInfo"/>
    <div class="el-dialog-div">
      <el-form ref="form" :model="form.check" :rules="rules" size="small" label-width="150px">
        <el-form-item label="考核名称" prop="checkName">
          <el-input v-model="form.check.checkName" maxlength="20" style="width: 370px;"/>
        </el-form-item>
        <el-form-item label="考核描述">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入考核描述"
            v-model="form.check.checkDesc">
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="form.check.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="form.check.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="封面图">
          <el-upload
            class="avatar-uploader"
            :action="fileUploadUrl"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload">
            <img v-if="coverImg" :src="coverImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="答题时限(分钟)">
              <el-input-number v-model.number="form.check.limeTime" :min="1" :max="999" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目数量">
              <el-input-number v-model.number="form.check.questionNum" :min="1" :max="999" controls-position="right"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单选题目数量">
              <el-input-number v-model.number="form.check.singleNum" :min="1" :max="999" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="判断题目数量">
              <el-input-number v-model.number="form.check.judgeNum" :min="1" :max="999" controls-position="right"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="合格分值">
          <el-input-number v-model.number="form.check.standardScore" :min="1" :max="999" controls-position="right"/>
        </el-form-item>
        <el-form-item label="题库">
          <el-link type="danger" @click="selectQuestion">选择题库</el-link>
        </el-form-item>
        <el-form-item label="题库列表">
          <el-tag v-for="bank in form.banks" :key="bank.bankId" closable @close="handleClose(bank)"> {{bank.bankName}}
          </el-tag>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { add, info } from '@/api/business/check'
  import questionBank from '../components/questionBank'

  export default {
    components: { questionBank },
    props: {
      isAdd: {
        type: Boolean,
        required: true
      }
    },
    data() {
      return {
        loading: false,
        dialog: false,
        fileUploadUrl: process.env.FILE_UPLOAD,
        coverImg: null,
        objCoverImg:[],
        form: {
          check: {
            id: null,
            checkName: '',
            checkDesc: '',
            coverImg: '',
            startTime: '',
            endTime: '',
            limeTime: 10,
            questionNum: '',
            singleNum: 1,
            judgeNum: 1,
            standardScore: 60
          },
          banks: []
        },
        rules: {
          checkName: [
            { required: true, message: '请输入考核名称', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      cancel() {
        this.dialog = false
        this.form = {
          check: {
            id: null,
            checkName: '',
            checkDesc: '',
            coverImg: '',
            startTime: '',
            endTime: '',
            limeTime: 10,
            questionNum: '',
            singleNum: 1,
            judgeNum: 1,
            standardScore: 60
          },
          banks: []
        }
      },
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.doAdd()
          }
        })
      },
      doAdd() {
        console.log(this.form)
        add(this.form).then(res => {
          this.$notify({
            title: '操作成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.init()
          this.cancel()
        }).catch(err => {
          this.loading = false
          console.log(err)
        })
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
      },
      handleSuccess(response, file, fileList) {
        this.objCoverImg = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.coverImg = uploadFile.url
        this.objCoverImg.push(uploadFile)
        this.form.check.coverImg = JSON.stringify(this.objCoverImg)
      },
      setQuestionInfo(data) {
        this.form.banks = data
        data.forEach(item => this.form.banks.push(item))
        this.form.banks = Array.from(new Set(this.form.banks))
      },
      selectQuestion() {
        this.$refs.questionBank.dialog = true
        this.$refs.questionBank.init()
      },
      handleClose(bank) {
        this.form.banks.splice(this.form.banks.indexOf(bank), 1)
      },
      getCheckInfo(checkId) {
        info(checkId).then(result => {
          this.form = result
          if(result.check.coverImg){
            let rowObj = JSON.parse(result.check.coverImg)
            this.coverImg = rowObj[0].url
          }
        })
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .el-dialog-div {
    height: 55vh;
    overflow-x: hidden;
  }
</style>
